package servlet;

import constant.ExamConstant;
import model.Patient;
import service.PatientService;
import util.EmailUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/send")
public class SendRecord extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        process(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        process(request, response);
    }

    protected void process(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Object type = request.getSession().getAttribute(ExamConstant.SESSION_LOGIN_TYPE);
        if (ExamConstant.LOGIN_TYPE_PATIENT.equals(type)) {
            try {
                Patient patient = (Patient) request.getSession().getAttribute(ExamConstant.SESSION_LOGIN_USER);
                String deptId = request.getParameter("deptId");
                
                if (deptId == null || deptId.trim().length() == 0) {
                    request.setAttribute("error", "科室选择有误");
                    request.getRequestDispatcher(ExamConstant.HOME_PAGE_QUERY).forward(request, response);
                    return;
                }
                
                // 执行挂号
                boolean success = PatientService.sendRegRecord(patient.getId(), deptId);
                
                if (success) {
                    // 发送邮件通知
                    String subject = "新病人挂号通知";
                    String body = String.format("患者 %s 已在您的科室预约挂号，请及时查看。", patient.getName());
                    EmailUtil.sendEmail("2790825892@qq.com", subject, body);
                    
                    response.sendRedirect(ExamConstant.HOME_PAGE_QUERY);
                } else {
                    request.setAttribute("error", "挂号失败，请重试");
                    request.getRequestDispatcher(ExamConstant.HOME_PAGE_PATIENT).forward(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "系统异常，请稍后重试");
                request.getRequestDispatcher(ExamConstant.HOME_PAGE_PATIENT).forward(request, response);
            }
        } else {
            request.setAttribute("error", "请先进行登录");
            request.getRequestDispatcher(ExamConstant.HOME_PAGE_LOGIN).forward(request, response);
        }
    }
}